package cc.sheji.Service;

import cc.sheji.domain.Admin;
import cc.sheji.exception.PasswordException;
import cc.sheji.reposity.AdminRepository;
import cc.sheji.util.EncoderUtil;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AdminService {
    @Autowired
    AdminRepository adminRepository;

    @Autowired
    EncoderUtil encoderUtil;


    public Object adminLogin(String name, String password) throws Exception {

        Admin user = adminRepository.findUserByName(name);
        System.out.println("password:" + password);
        String passwordEncode = encoderUtil.encodeStr(password);
        if (user == null) {
            throw new PasswordException();
        }
        System.out.println("passwordEncode:" + passwordEncode);
        if (!passwordEncode.equals(user.getPassword())) {
            throw new PasswordException();
        }
        StpUtil.login(user.getId());
        HashMap returnData = new HashMap();
        ArrayList<String> roles=new ArrayList<>();
        roles.add("admin");
        returnData.put("token",StpUtil.getTokenValue());
        returnData.put("roles",roles);
        returnData.put("introduction","I am a super administrator");
        returnData.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        returnData.put("name","Super Admin");
       return returnData;
    }






    private HashMap<String, Object> adminInfo(Admin user) {

        HashMap returnData = new HashMap();
        ArrayList<String> roles=new ArrayList<>();
        roles.add("admin");
        returnData.put("roles",roles);
        returnData.put("introduction","I am a super administrator");
        returnData.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        returnData.put("name","Super Admin");
        return returnData;
    }



    public HashMap<String, Object> getAdmin() {

      //  Admin user = adminRepository.findById(Long.parseLong("" + StpUtil.getLoginId())).get();
        HashMap returnData = adminInfo(null);
        return returnData;
    }

    public List<Admin> list() {

        return adminRepository.findAll(null);
    }

    public HashMap create(Admin user) {

        user.setPassword(encoderUtil.encodeStr(user.getPassword()));
        user = adminRepository.save(user);
       // StpUtil.login(user.getId());
        HashMap returnData = adminInfo(user);
        return returnData;
    }

    public Admin update(Admin user) {

        Admin user1 = adminRepository.findById(user.getId()).get();
        user.setName(user1.getName());
        Admin returnData = adminRepository.save(user);
        return returnData;
    }

}
